package com.zhilianbao.leyaogo.ui.fragment.me;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bql.commonrow.CommonListRow;
import com.bql.utils.CheckUtils;
import com.bql.utils.EventManager;
import com.bql.utils.StringUtils;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.app.LeYaoGoApplication;
import com.zhilianbao.leyaogo.constants.CacheConfig;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.events.UserEventCode;
import com.zhilianbao.leyaogo.http.api.AccountApi;
import com.zhilianbao.leyaogo.http.callback.JsonCallback;
import com.zhilianbao.leyaogo.model.response.UserLoginInfo;
import com.zhilianbao.leyaogo.model.response.me.MeRedDotResponse;
import com.zhilianbao.leyaogo.model.response.me.UserDetailsInfo;
import com.zhilianbao.leyaogo.ui.activity.me.ServiceAndHelpActivity;
import com.zhilianbao.leyaogo.ui.activity.me.mes.MessageActivity;
import com.zhilianbao.leyaogo.ui.activity.me.moneyaccount.BalanceActivity;
import com.zhilianbao.leyaogo.ui.activity.me.moneyaccount.CardVoucherActivity;
import com.zhilianbao.leyaogo.ui.activity.me.moneyaccount.CouponActivity;
import com.zhilianbao.leyaogo.ui.activity.me.myorder.MyOrderActivity;
import com.zhilianbao.leyaogo.ui.activity.me.setting.SettingActivity;
import com.zhilianbao.leyaogo.ui.activity.me.userinfo.MyCollectionActivity;
import com.zhilianbao.leyaogo.ui.activity.me.userinfo.UserInfoActivity;
import com.zhilianbao.leyaogo.ui.fragment.base.BaseFragment;
import com.zhilianbao.leyaogo.utils.ImageUtils;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.utils.XToastUtils;
import com.zlb.lxlibrary.common.utils.LeXiuUserManger;
import com.zlb.lxlibrary.service.LeXiuInitService;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;


/**
 * ClassName: MeFragment <br>
 * Description: 我 Fragment<br>
 * Author: liu <br>
 */
public class MeFragment extends BaseFragment {
    @BindView(R.id.iv_me_setting)
    ImageView mIvMeSetting;
    @BindView(R.id.balance_num)
    TextView balanceNum;
    @BindView(R.id.coupon_num)
    TextView couponNum;
    @BindView(R.id.card_voucher_num)
    TextView cardVoucherNum;
    @BindView(R.id.service_help)
    RelativeLayout mServiceHelp;
    @BindView(R.id.user_center)
    ImageView mUserLogin;
    @BindView(R.id.rl_wait_to_pay)
    RelativeLayout mRlWaitToPay;
    @BindView(R.id.rl_wait_to_send)
    RelativeLayout mRlWaitToSend;
    @BindView(R.id.rl_sending)
    RelativeLayout mRlSending;
    @BindView(R.id.rl_sale_after)
    RelativeLayout mRlSaleAfter;
    @BindView(R.id.see_all_order)
    CommonListRow mSeeAllOrder;
    @BindView(R.id.iv_message)
    ImageView mIvMessage;
    @BindView(R.id.rl_me_top)
    RelativeLayout mRlMeTop;
    @BindView(R.id.row_my_collection)
    CommonListRow mRowMyCollection;
    @BindView(R.id.ll_le_pai)
    LinearLayout llLePai;
    @BindView(R.id.ll_repeat)
    LinearLayout llRepeat;
    @BindView(R.id.ll_fans)
    LinearLayout llFans;
    @BindView(R.id.ll_attention)
    LinearLayout llAttention;
    @BindView(R.id.tv_user_name)
    TextView mTvUserName;
    @BindView(R.id.wait_to_pay_num)
    TextView waitToPayNum;
    @BindView(R.id.wait_to_send_num)
    TextView waitToSendNum;
    @BindView(R.id.sending_num)
    TextView sendingNum;
    @BindView(R.id.finish_num)
    TextView finishNum;
    @BindView(R.id.ll_balance)
    LinearLayout mLlBanlance;
    @BindView(R.id.ll_coupons)
    LinearLayout mLlCoupons;
    @BindView(R.id.ll_card_voucher)
    LinearLayout mLlCardVoucher;
    private String myOrder;
    private Intent mIntent;
    private String myCollection;
    private UserLoginInfo mUserLoginInfo;
    private boolean userLogin;
    private UserDetailsInfo mUserDetailsInfo;
    private MeRedDotResponse mMeRedDotResponse;

    public static MeFragment getInstance() {
        MeFragment fragment = new MeFragment();
        return fragment;
    }

    /**
     * 页面被杀,重启页面时初始化数据
     *
     * @param savedInstanceState
     */
    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
        setUseDate();
    }

    @Override
    protected void initToolbarHere() {
    }

    @Override
    protected boolean lazyLoadMode() {
        return true;
    }

    @Override
    protected void initLazyViewsAndEvents(@Nullable Bundle savedInstanceState) {
        super.initLazyViewsAndEvents(savedInstanceState);
        setUseDate();
    }

    private void setUseDate() {
        userLogin = Utils.justIsUserLogin();
        if (userLogin) {//用户已登录
            setLoginData();
        } else {//用户未登录
            setUnLoginData();
        }
        setData();
    }

    private void setLoginData() {
        mUserLoginInfo = Utils.getUserLoginInfo();
        mUserDetailsInfo = Utils.getUserInfo();
        if (mUserDetailsInfo == null) {
            //用户登录,请求个人详情数据
            loadUserDetailInfoData();
        } else {
            setUserNickName();
        }
        ImageUtils.loadSmallAvatar(Utils.returnUrlShow(mUserLoginInfo.getUserPic()), mUserLogin);
        setRedDotData();
    }

    //请求用户详情信息
    private void loadUserDetailInfoData() {
        AccountApi.getUserInfo(mActivity, mUserLoginInfo.getUserId(), mUserLoginInfo.getTokenId(), mUserLoginInfo.getUserId(), new JsonCallback<UserDetailsInfo>(mActivity) {

            @Override
            public void onSuccess(UserDetailsInfo userDetailsInfo, Call call, Response response) {
                mUserDetailsInfo = userDetailsInfo;
                setUserNickName();
                Utils.putUserInfo(userDetailsInfo);
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                mTvUserName.setText(mUserLoginInfo.getUserMobile());
            }
        });
    }

    private void setUserNickName() {
        if (CheckUtils.isEmpty(mUserDetailsInfo.getNickName())) {
            mTvUserName.setText(mUserLoginInfo.getUserMobile());
        } else {
            mTvUserName.setText(mUserDetailsInfo.getNickName());
        }
    }

    private void setUnLoginData() {
        mTvUserName.setText("登录/注册");
        ImageUtils.loadSmallAvatar("", mUserLogin);
        setAccountNum("-", "-", "-", View.INVISIBLE);
    }


    //设置我的页面红点和账户数据
    private void setRedDotData() {
        mMeRedDotResponse = Utils.getMeRedDot();
        if (mMeRedDotResponse == null) {
            loadRedData();
        } else {
            setAccountNum(mMeRedDotResponse.getAvailableBalance() + "", mMeRedDotResponse.getCoupons() + "", mMeRedDotResponse.getRechargeCard() + "", View.VISIBLE);
            setOrderNum(mMeRedDotResponse);
        }
    }

    //网络请求红点和账户数据
    public void loadRedData() {
        if (mUserLoginInfo == null) {
            setUnLoginData();
            setData();
            return;
        }
        AccountApi.getMyRedDotValue(mActivity, mUserLoginInfo.getUserId(), Utils.getSupplierId(), new JsonCallback<MeRedDotResponse>(mActivity) {
            @Override
            public void onSuccess(MeRedDotResponse meRedDotResponse, Call call, Response response) {
                mMeRedDotResponse = meRedDotResponse;
                Utils.putMeRedDot(meRedDotResponse);
                setAccountNum(mMeRedDotResponse.getAvailableBalance() + "", mMeRedDotResponse.getCoupons() + "", mMeRedDotResponse.getRechargeCard() + "", View.VISIBLE);
                setOrderNum(mMeRedDotResponse);
            }
        });
    }

    //设置账户数据和订单数显示
    private void setAccountNum(String textBalanceNum, String textCouponNum, String textCardVoucherNum, int visible) {
        balanceNum.setText(textBalanceNum);
        couponNum.setText(textCouponNum);
        cardVoucherNum.setText(textCardVoucherNum);
        waitToPayNum.setVisibility(visible);
        waitToSendNum.setVisibility(visible);
        sendingNum.setVisibility(visible);
        finishNum.setVisibility(visible);
    }

    //设置订单的数据
    private void setOrderNum(MeRedDotResponse meResponse) {
        if (meResponse.getPendingPayment() != 0) {
            waitToPayNum.setText(meResponse.getPendingPayment() + "");
        } else {
            waitToPayNum.setVisibility(View.GONE);
        }
        if (meResponse.getToBeShipped() != 0) {
            waitToSendNum.setText(meResponse.getToBeShipped() + "");
        } else {
            waitToSendNum.setVisibility(View.GONE);
        }
        if (meResponse.getDistributionIn() != 0) {
            sendingNum.setText(meResponse.getDistributionIn() + "");
        } else {
            sendingNum.setVisibility(View.GONE);
        }
        if (meResponse.getCompleted() != 0) {
            finishNum.setText(meResponse.getCompleted() + "");
        } else {
            finishNum.setVisibility(View.GONE);
        }
    }

    /**
     * 如果是懒加载模式  该方法用不到
     *
     * @param savedInstanceState
     */
    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {

    }

    //设置信息
    private void setData() {
        myOrder = StringUtils.isEmpty("查看所有订单", "");
        myCollection = StringUtils.isEmpty("", "");
        mSeeAllOrder.setStatusText(myOrder);
        mSeeAllOrder.setStatusTextSize(13);
        mSeeAllOrder.setStatusTextColor(getResources().getColor(R.color.color_999999));
        mRowMyCollection.setStatusText(myCollection);
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_me_user;
    }

    @Override
    public boolean isHideToolbarLayout() {
        return true;
    }

    @OnClick({R.id.iv_me_setting, R.id.ll_balance, R.id.ll_coupons, R.id.ll_card_voucher, R.id.iv_message, R.id.user_center, R.id.rl_wait_to_pay,
            R.id.rl_wait_to_send, R.id.rl_sending, R.id.rl_sale_after, R.id.see_all_order, R.id.service_help, R.id.row_my_collection, R.id.ll_le_pai, R.id.ll_repeat, R.id.ll_fans, R.id.ll_attention})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_me_setting://设置
                Utils.startActivity(mActivity, SettingActivity.class);
                break;
            case R.id.iv_message://消息
                if (userLogin) {
                    Utils.startActivity(mActivity, MessageActivity.class);
                } else {
                    Utils.gotoLogin();
                }
                break;
            case R.id.ll_balance://余额
                if (userLogin) {
                    Utils.startActivity(mActivity, BalanceActivity.class);
                } else {
                    Utils.gotoLogin();
                }
                break;
            case R.id.ll_coupons://优惠券
                if (userLogin) {
                    Utils.startActivity(mActivity, CouponActivity.class);
                } else {
                    Utils.gotoLogin();
                }
                break;
            case R.id.ll_card_voucher://卡券
                if (userLogin) {
                    Utils.startActivity(mActivity, CardVoucherActivity.class);
                } else {
                    Utils.gotoLogin();
                }
                break;
            case R.id.user_center://个人信息
                if (userLogin) {
                    if (mUserDetailsInfo == null) {
                        XToastUtils.showShortToast("获取用户信息失败,请重新登录");
                        Utils.gotoLogin();
                    } else {
                        //                        Bundle bundle = new Bundle();
                        //                        bundle.putSerializable(IntentConfig.USER_DETAIL_INFO, mUserDetailsInfo);
                        //                        Utils.startActivity(mActivity, UserInfoActivity.class, bundle);
                        Utils.startActivity(mActivity, UserInfoActivity.class);
                    }
                } else {
                    Utils.gotoLogin();
                }
                break;
            //viewPager选中页面 全部0,代付款1,代发货2,配送中3,待评价4
            case R.id.rl_wait_to_pay://待支付
                if (userLogin) {
                    mIntent = new Intent(mActivity, MyOrderActivity.class);
                    mIntent.putExtra("num", 1);
                    startActivity(mIntent);
                } else {
                    Utils.gotoLogin();
                }
                break;
            case R.id.rl_wait_to_send://待发货
                if (userLogin) {
                    mIntent = new Intent(mActivity, MyOrderActivity.class);
                    mIntent.putExtra("num", 2);
                    startActivity(mIntent);

                } else {
                    Utils.gotoLogin();
                }
                break;
            case R.id.rl_sending://配送中
                if (userLogin) {
                    mIntent = new Intent(mActivity, MyOrderActivity.class);
                    mIntent.putExtra("num", 3);
                    startActivity(mIntent);

                } else {
                    Utils.gotoLogin();
                }
                break;
            case R.id.rl_sale_after://售后退款
                if (userLogin) {
                    mIntent = new Intent(mActivity, MyOrderActivity.class);
                    mIntent.putExtra("num", 4);
                    startActivity(mIntent);

                } else {
                    Utils.gotoLogin();
                }
                break;
            case R.id.see_all_order://查看全部订单
                if (userLogin) {
                    mIntent = new Intent(mActivity, MyOrderActivity.class);
                    mIntent.putExtra("num", 0);
                    startActivity(mIntent);
                } else {
                    Utils.gotoLogin();
                }

                break;
            case R.id.service_help://客服与帮助
                Utils.startActivity(mActivity, ServiceAndHelpActivity.class);
                break;
            case R.id.row_my_collection://我的收藏
                if (userLogin) {
                    Utils.startActivity(mActivity, MyCollectionActivity.class);
                } else {
                    Utils.gotoLogin();
                }
                break;
            case R.id.ll_le_pai://乐拍
                if (userLogin) {
                    LeXiuInitService.getInstance().jumpLeXiu().jumpToUserMainActivity(mActivity, LeXiuUserManger.getInstance().getUserID(mActivity), 0);

                } else {
                    Utils.gotoLogin();
                }
                break;
            case R.id.ll_repeat://转发
                if (userLogin) {
                    LeXiuInitService.getInstance().jumpLeXiu().jumpToUserMainActivity(mActivity, LeXiuUserManger.getInstance().getUserID(mActivity), 1);
                } else {
                    Utils.gotoLogin();
                }
                break;
            case R.id.ll_fans://粉丝
                if (userLogin) {
                    LeXiuInitService.getInstance().jumpLeXiu().jumpToUserMainActivity(mActivity, LeXiuUserManger.getInstance().getUserID(mActivity), 3);
                } else {
                    Utils.gotoLogin();
                }
                break;
            case R.id.ll_attention://关注
                if (userLogin) {
                    LeXiuInitService.getInstance().jumpLeXiu().jumpToUserMainActivity(mActivity, LeXiuUserManger.getInstance().getUserID(mActivity), 2);
                } else {
                    Utils.gotoLogin();
                }
                break;
        }
    }

    @Override
    public boolean registerEventBus() {
        return true;
    }

    @Override
    protected void onHandleEvent(EventManager eventManager) {
        super.onHandleEvent(eventManager);
        switch (eventManager.getEventCode()) {
            case LeEventCode.MSG_CODE_LOGIN_SUCCESS://登录成功
                setUseDate();
                break;
            case LeEventCode.MSG_CODE_OUT_LOGIN://退出登录
                LeYaoGoApplication.getDataKeeper().remove(CacheConfig.ME_RED_DOT);
                mUserLoginInfo = null;
                mMeRedDotResponse = null;
                mUserDetailsInfo = null;
                setUseDate();
                break;
            //            case LeEventCode.MSG_CODE_ADD_ORDER://添加订单成功
            case LeEventCode.MSG_CODE_ORDER_CANCEL://取消订单
            case LeEventCode.MSG_CODE_SURE_RECEIVE://确认收货
            case LeEventCode.MSG_CODE_ORDER_DETAIL_CANCEL://订单详情取消订单
            case LeEventCode.MSG_CODE_ORDER_DETAIL_SURE_RECEIVE://订单详情确认收货
            case LeEventCode.MSG_CODE_ALI_PAY_SUCCESS://支付宝支付成功
            case LeEventCode.MSG_CODE_PAY_SUCCESS://微信支付成功
            case LeEventCode.MSG_CODE_YUE_PAY_SUCCESS://余额支付成功
            case LeEventCode.MSG_CODE_BALANCE_ADD_ORDER_SUCCESS://余额充值添加订单成功
            case LeEventCode.MSG_CODE_CARD_VOUCHER_ACTIVATE_SUCCESS://卡券激活成功
                loadRedData();
                break;
            case UserEventCode.MSG_CODE_MODIFY_USERINFO://用户更新个人信息
                setLoginData();
                break;
        }
    }
}
